<?php

function farmer_add_page() {
    return drupal_get_form('farmer_edit_form');
}

function farmer_edit_page($id) {
    return drupal_get_form('farmer_edit_form', $id);
}

function farmer_account_page() {
    global $user;
    return drupal_get_form('farmer_edit_form', $user->uid);
}
function farmer_upgrade_page() {
    global $user;
    $user_info = _get_user_info($user->uid);
    $employee_roles = array('administrator',  '销售员', '销售管理员', '农化管理员', '农化服务员','公司领导');
    $distributor_roles = array('经销商','升级成经销商');
    if($user_info['role'] == "authenticated user"){
        $role_result = user_role_load_by_name('升级成农户');
        $new_user = array(
            'signature_format' => 'filtered_html',
            'status' => 1,
            'language' => 'zh-hans',
            'timezone' => 'Asia/Shanghai',
            'roles' => array(
                $role_result->rid =>  '升级成农户',
            ),
        );
        $account = user_save($user, $new_user);
        drupal_static_reset("user_access");
        $user_info = _get_user_info($user->uid);
        insertDefaultFarmer($user->uid);
    }else if(in_array($user_info['role'],$employee_roles)||in_array($user_info['role'],$distributor_roles)){
        drupal_goto('/user');
    }
    insertDefaultFarmer($user->uid);
    return drupal_get_form('farmer_edit_form',$user->uid);
}
function farmer_edit_form($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {//修改用户信息
        if($user->uid == 0){//匿名用户
            drupal_goto('farmer/add');
        }else {
            $user_info = _get_user_info($user->uid);
            if($user_info['role'] === '农户' ||$user_info['role'] === '升级成农户' ){//农户只能查看修改自己的信息,其他角色通过“权限”控制页面控制
                $id = $user->uid;
                $form_state['build_info']['args'][0] = $id;
            }
        }
        $record = nonghua_data_load('farmer', 'farmer_id', $id);
        $account = user_load($id);

        $form_state['account'] = $account;
        if (empty($account)&&empty($record)) {
            drupal_set_message(t('农户不存在！'), 'status', FALSE);
            return $form;
        }
        $form_state['update'] = true;
    }else{//添加用户
        $form_state['insert'] = true;
        if($user->uid == 0){//匿名用户
            drupal_goto('account/register');
        }else{
            $user_info = _get_user_info($user->uid);
            if($user_info['role'] === '农户'){//农户没有权限,其他角色通过“权限”控制页面控制
                drupal_goto('account/farmer');
            }
            $isLogged = true;
        }

    }

    // 判断用户角色
    if (!nonghua_user_access('farmer', 'view', $id, !empty($record) ? $record->author_uid : 0, $id)) {
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }

    $form['#attributes'] = array('class' => array('farmer-edit-form'));
    $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,$record->distributor_id);
    $form['farmer_name'] = array(
        '#type' => 'textfield',
        '#title' => '姓名',
        '#default_value' => !empty($record) ? trim($record->farmer_name) : '',
        '#size' => 32,
        '#maxlength' => 10,
//        '#required' => TRUE,
    );
    $gender_options = array('男' => '男', '女' => '女');
    $form['gender'] = array(
        '#type' => 'radios',
        '#title' => '性别',
        '#default_value' => !empty($record) ? $record->gender : '男',
        '#options' => $gender_options,
    );

    if (!empty($_GET['addr_id'])) {
        $form_state['addr_id'] = $_GET['addr_id'];
        $form['#addr_id'] = $_GET['addr_id'];
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE, $form_state['addr_id'] ,'');
    }else{
        $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state,isset($record) && !empty($record)?$record->addr_id:'');
        $form['address'] = _insert_address_selection_form($form, $form_state,'address', 5, TRUE,  !empty($record) ? $record->addr_id:'','');
    }
    if (!empty($form_state['addr_id'])) {
        $form['#addr_id'] = $form_state['addr_id'];
    }
    // 导入农户
    $form['#attributes']['enctype'] = 'multipart/form-data';
    $form['file']['file_upload'] = array(
        '#type' => 'file',
        '#title' => '批量导入',
        '#size' => 48
    );

    $form['file']['submit'] = array(
        '#type' => 'submit',
        '#value' => '导入农户',
    );

    $form['details'] = array(
        '#type' => 'textfield',
        '#title' => '详细地址',
        '#default_value' => !empty($record) ? $record->addr_details : '',
        '#size' => 32,
        '#maxlength' => 50,
//        '#required' => TRUE,
    );
    insert_special_activities($form,$form_state,$record);

    $form['phone'] = array(
        '#type' => 'textfield',
        '#title' => '电话（例如：010 12345678  或者 010-12345678 或者 010--12345678）',
        '#default_value' => !empty($record) ? $record->phone : '',
        '#size' => 32,
        '#maxlength' => 20,
    );

    $form['cell'] = array(
        '#type' => 'textfield',
        '#title' => '手机',
        '#default_value' => !empty($record) ? $record->cell : '',
        '#size' => 32,
        '#maxlength' => 20,
//        '#required' => TRUE,
    );

    $form['email'] = array(
        '#type' => 'textfield',
        '#title' => '电子邮件',
        '#default_value' => !empty($record) ? $record->email : '',
        '#size' => 32,
        '#maxlength' => 40,
    );

    $form['type'] = array(
        '#type' => 'textfield',
        '#title' => '农户类型',
        '#default_value' => !empty($record) ? $record->type : '',
        '#size' => 32,
        '#maxlength' => 10,
    );
    $form['farm_area'] = array(
        '#type' => 'textfield',
        '#title' => '耕地面积',
        '#default_value' => !empty($record) ? $record->farm_area : '0',
//        '#size' => 32,
//        '#maxlength' => 8,
    );

    $form['soil_type'] = array(
        '#type' => 'textfield',
        '#title' => '土壤种类',
        '#default_value' => !empty($record) ? $record->soil_type : '',
        '#size' => 32,
        '#maxlength' => 10,
    );

    $form['soil_fertility'] = array(
        '#type' => 'textfield',
        '#title' => '土壤肥沃程度',
        '#default_value' => !empty($record) ? $record->soil_fertility : '',
        '#size' => 32,
        '#maxlength' => 10,
    );

    $form['farmer_other']['comments'] = array(
        '#type' => 'textarea',
        '#title' => '备注',
        '#default_value' => !empty($record) ? $record->comments : '',
        '#cols' => 50,
        '#rows' => 2,
        '#maxlength'=>50,
        '#attributes'=>array('placeholder'=>'最多输入50字。')
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => '提交',
        '#access' => isset($form['#upgrade_user']) && !empty($form['#upgrade_user'])?true:nonghua_user_access('farmer', 'edit', $id, !empty($record) ? $record->author_uid:0,$id),
        '#validate' => array('farmer_edit_form_submit_validate'),
    );
    return $form;
}

function farmer_edit_form_submit_validate($form, &$form_state) {
    global $user;
    $user_info = _get_user_info();
    $id =  isset($form_state['build_info']['args'][0])&&!empty($form_state['build_info']['args'][0])?$form_state['build_info']['args'][0]:$user->uid;
    pregPN_E_TP($form_state['values']['cell'],$form_state['values']['phone'],$form_state['values']['email']);
        _address_element_validate($form_state);
    if(empty($form_state['values']['farmer_name'])){
        form_set_error('farmer_name', "农户姓名不能为空");
    }
    if(empty($form_state['values']['cell'])){
        form_set_error('cell', "农户电话不能为空");
    }
    if(!empty($form_state['values']['farm_area'])){
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if(!preg_match ($reg, $form_state['values']['farm_area']) || (strlen(explode('.',$form_state['values']['farm_area'])[0])>8)) {
            form_set_error('farm_area', "耕地面积格式有误。");
        }
    }
    if(isset($form_state['insert']) && $form_state['insert']) {
      
        if (isset($form_state['values']['cell'])&&!empty($form_state['values']['cell'])) {//注册
//            $account = user_load($id);
            if ($error = user_validate_name($form_state['values']['cell'])) {
                form_set_error('cell', $error);
            }
            elseif ((bool) db_select('users')->fields('users', array('uid'))->condition('name', db_like($form_state['values']['cell']), 'LIKE')->range(0, 1)->execute()->fetchField()) {
                form_set_error('cess', t('The name %name is already taken.', array('%name' => $form_state['values']['cell'])));
            }
        }

//        $address = _get_address_id($form_state);
//        if (!empty($form_state['values']['farmer_name']) &&  !empty($address)) {
//            $record = db_select('farmer', 'u')
//                ->condition('u.farmer_name', $form_state['values']['farmer_name'])
//                ->condition('u.addr_id', $address)
//                ->fields('u')
//                ->execute()->fetchAssoc();
//            if (!empty($record)) {
//                form_set_error('farmer_name', "该农户已存在！");
//            }
//        }
        if(!empty($form_state['values']['distributor_name'])){
            $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false);
            if(empty($distributor_id)){
                form_set_error('distributor_name', "经销商信息不存在！");
            }
        }
    }

    if(isset($form_state['update']) && $form_state['update']) {

//        if (!empty($form_state['values']['farmer_name']) &&  !empty($address)) {
//            $record = db_select('farmer', 'u')
//                ->condition('u.farmer_name', $form_state['values']['farmer_name'])
//                ->condition('u.addr_id', $address)
//                ->condition('u.farmer_id', $id,'!=')
//                ->fields('u')
//                ->execute()->fetchAssoc();
//            if (!empty($record)) {
//                form_set_error('farmer_name', "该农户已存在！");
//            }
//        }

    }
}

function farmer_edit_form_submit($form, &$form_state) {
    if($form_state['values']['op'] == '导入农户'){
        if(_address_element_validate($form_state)){
            if(!empty($_FILES['files']['name']['file_upload'])){
                metercomm_import_form_submit($form, $form_state);
                drupal_goto('farmer/list');
            }else{
                form_set_error('file_upload', "未选择Excel表格");
            }
        }
    }else{
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    $address =  _get_address_id_from_autocomplete_select($form_state);
    $transaction = db_transaction();
    $user_info = _get_user_info();
    if($user_info['role'] == "升级成农户"){
        $id = $user->uid;
    }
    try {
        if (empty($id)) { //add new farmer
            $role_result = user_role_load_by_name('农户');
            $new_user = array(
                'name' => isset($form_state['values']['name']) && !empty($form_state['values']['name']) ? $form_state['values']['name'] : $form_state['values']['cell'],
                'pass' => isset($form_state['values']['pass']) && !empty($form_state['values']['pass']) ? $form_state['values']['pass'] : '123456',
                'mail' => isset($form_state['values']['email']) ? $form_state['values']['email'] : null,
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' => isset($form_state['values']['email']) ? $form_state['values']['email'] : null,
                'roles' => array(
                    $role_result->rid => '农户',
                ),
            );
            $account = user_save('', $new_user);
            $nid = db_insert('farmer')// Table name no longer needs {}
            ->fields(array(
                'farmer_id' => $account->uid,
                'farmer_name' => trim($form_state['values']['farmer_name']),
                'gender' => isset($form_state['values']['gender'])&& !empty($form_state['values']['gender'])?$form_state['values']['gender']:null,
                'addr_id' => $address,
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'addr_details' => isset($form_state['values']['details'])&& !empty($form_state['values']['details'])?$form_state['values']['details']:null,
                'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
                'type' => isset($form_state['values']['type'])&& !empty($form_state['values']['type'])?$form_state['values']['type']:null,
                'phone' => isset($form_state['values']['phone'])&& !empty($form_state['values']['phone'])?$form_state['values']['phone']:null,
                'cell' => isset($form_state['values']['cell'])&& !empty($form_state['values']['cell'])?$form_state['values']['cell']:null,
                'email' => isset($form_state['values']['email'])&& !empty($form_state['values']['email'])?$form_state['values']['email']:null,
                'farm_area' => isset($form_state['values']['farm_area']) && !empty($form_state['values']['farm_area']) ? $form_state['values']['farm_area'] : '0',
                'soil_type' => isset($form_state['values']['soil_type']) && !empty($form_state['values']['soil_type'])?$form_state['values']['soil_type']:null,
                'soil_fertility' => isset($form_state['values']['soil_fertility'])&& !empty($form_state['values']['soil_fertility'])?$form_state['values']['soil_fertility']:null,
                'comments' => isset($form_state['values']['comments'])&& !empty($form_state['values']['comments'])?$form_state['values']['comments']:null,
                'status'=>'农户',
                'author_uid' => $user->uid,
                'timestamp' => time(),))
                ->execute();

            if($user->uid == 0){//匿名用户
//                insert_chat_for_chat($account->uid,$form_state['values']['farmer_name'],$address);
                drupal_set_message(t('注册成功,请登录！'), 'status', FALSE);
                drupal_goto('user/login');
            }
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            if(!empty($_GET['addr_id'])){
                drupal_goto('farmer/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }
            drupal_goto('farmer/edit/'.$nid,array('query' => array('farmer_id' => $nid)));

        } else {
            $new_user = array(
//                'name' => !empty($form_state['values']['name']) ? $form_state['values']['name'] : $form_state['values']['cell'],
//                'pass' => !empty($form_state['values']['pass']) ? $form_state['values']['pass'] : '123456',
                'mail' => isset($form_state['values']['email'])?$form_state['values']['email']:null,
                'signature_format' => 'filtered_html',
                'status' => 1,
                'language' => 'zh-hans',
                'timezone' => 'Asia/Shanghai',
                'init' =>isset($form_state['values']['email'])?$form_state['values']['email']:null,
            );
            $account = $form_state['account'];
            user_save($account, $new_user);

            $nid = db_update('farmer')// edit exsting store. todo: update only modified fields
            ->fields(array(
                'farmer_name' => trim($form_state['values']['farmer_name']),
                'gender' => isset($form_state['values']['gender'])&& !empty($form_state['values']['gender'])?$form_state['values']['gender']:null,
                'addr_id' => $address,
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'addr_details' => isset($form_state['values']['details'])&& !empty($form_state['values']['details'])?$form_state['values']['details']:null,
                'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
                'type' => isset($form_state['values']['type'])&& !empty($form_state['values']['type'])?$form_state['values']['type']:null,
                'phone' => isset($form_state['values']['phone'])&& !empty($form_state['values']['phone'])?$form_state['values']['phone']:null,
                'cell' => isset($form_state['values']['cell'])&& !empty($form_state['values']['cell'])?$form_state['values']['cell']:null,
                'email' => isset($form_state['values']['email'])&& !empty($form_state['values']['email'])?$form_state['values']['email']:null,
                'farm_area' => isset($form_state['values']['farm_area']) && !empty($form_state['values']['farm_area']) ? $form_state['values']['farm_area'] : '0',
                'soil_type' => isset($form_state['values']['soil_type']) && !empty($form_state['values']['soil_type'])?$form_state['values']['soil_type']:null,
                'soil_fertility' => isset($form_state['values']['soil_fertility'])&& !empty($form_state['values']['soil_fertility'])?$form_state['values']['soil_fertility']:null,
                'comments' => isset($form_state['values']['comments'])&& !empty($form_state['values']['comments'])?$form_state['values']['comments']:null,
                'timestamp' => time(),))
                ->condition('farmer_id', $id, '=')
                ->execute();

            if(!isset( $form_state['mobile_service'])|| !$form_state['mobile_service']){
                if($user_info['role'] === '农户' && $user->uid === $id){
                    drupal_set_message(t('修改成功！'), 'status', FALSE);
                    drupal_goto('farmer/edit/'.$user->uid,['query'=>['farmer_id'=>$user->uid]]);
                }elseif($user_info['role'] === '升级成农户'){
                    drupal_goto('account/upgrade/result/1');
                }
                drupal_set_message(t('修改成功！'), 'status', FALSE);
                if(!empty($_GET['addr_id'])){
                    drupal_goto('farmer/list',array('query' => array('addr_id' => $_GET['addr_id'])));
                }
                drupal_goto('farmer/edit/'.$id,array('query' => array('farmer_id' =>$id)));
            }

        }
    } catch (Exception $e) {
        $transaction->rollback();
        watchdog_exception('user', $e);
        if( $user_info['role'] == "升级成农户"){
            drupal_goto('account/upgrade/result/0');
        }
        drupal_set_message(t('操作失败！').$e->getMessage(), 'status', FALSE);
    }
    }
}

function get_agent_by_addr($addr_id){
    $res = db_select('online_agent','OA')
        ->fields('OA')
        ->condition('OA.addr_id',$addr_id,'=')
        ->execute()->fetchAll();
    if($res){
        return $res;
    }else{
        $addr_ids = get_parentAddr_id($addr_id);
        $res = db_select('online_agent','OA')
            ->fields('OA')
            ->condition('OA.addr_id',$addr_ids,'in')
            ->execute()->fetchAll();
        return $res;
    }
}


function insert_chat_for_chat($farmer_id,$farmer_name,$addr_id){
    $agent_ids = get_agent_by_addr($addr_id);
    foreach($agent_ids as $agent_id){
        $isset_chat = isset_chat_user_load($agent_id->uid,$farmer_id);
        if(!$isset_chat){
            $chat_id = db_insert('chat')
                ->fields(array(
                    'title' =>$agent_id->uid."&".$farmer_id,
                    'timestamp' => 0,
                    'type' => 0,
                    'active' => 1))
                ->execute();
            $add_user = db_insert('chat_users')
                ->fields(array(
                    'chat_id' => $chat_id,
                    'user_id' => $agent_id->uid,
                    'nickname' => $agent_id->chat_group_id == 1 ? '咨询客服' : '投诉客服',
                    'chat_group_id'=>$agent_id->chat_group_id,
                    'active' => 1,
                    'checkpoint' => 0))
                ->execute();
            $add_user1 = db_insert('chat_users')
                ->fields(array(
                    'chat_id' => $chat_id,
                    'user_id' => $farmer_id,
                    'nickname' => $farmer_name,
                    'chat_group_id' => $agent_id->chat_group_id ,
                    'active' => 1,
                    'checkpoint' => 0))
                ->execute();
        }
    }
}
